<template>
  <div class="container" id="view">
    <el-row
      :gutter="20"
      type="flex"
      justify="center"
      style="margin-bottom: 10px"
    >
      <el-button type="primary" plain size="small" @click="active = 1"
        >电脑</el-button
      >
      <el-button type="warning" plain size="small" @click="active = 2"
        >平板</el-button
      >
      <el-button type="success" plain size="small" @click="active = 3"
        >手机</el-button
      >
    </el-row>

    <el-card
      v-if="active == 1"
      shadow="always"
      :body-style="{ padding: '20px 0', height: '100vh' }"
    >
      <div slot="header" style="text-align: center; font-size: 20px">
        {{ title }}
      </div>

      <el-form :model="{ formList }" ref="form" label-width="0" size="small">
        <item
          v-for="(item, index) in formList"
          :node="item"
          :index="index"
          :key="'item_' + index"
          :showmessage="true"
          @currentNode="() => {}"
          @deleteNode="() => {}"
          @Node="() => {}"
        ></item>
        <el-col v-if="formList.length" :span="24" :offset="0">
          <el-form-item style="width: 100%">
            <div>
              <el-button
                type="primary"
                style="width: 90%; margin-left: 5%"
                size="default"
                @click="submit()"
                >提交</el-button
              >
            </div>
          </el-form-item></el-col
        >
      </el-form>
    </el-card>

    <div v-else class="phone">
      <iframe
        :style="{ width: active == 2 ? '50vw' : active == 3 ? '25vw' : 0 }"
        :src="`/#/mobile?id=${id}`"
        frameborder="0"
      ></iframe>
    </div>
  </div>
</template>

<script>
import item from "../edit/item.vue";
import { getSurvey, submitSurvey, uploadImage } from "@/api/form";
import { debounce, Base64toFile } from "@/utils/index";
export default {
  components: { item },
  data() {
    return {
      active: 1,
      formList: [],
      logicList: [],
      id: 25,
      title: "",
    };
  },

  created() {
    this.debounceInit = debounce(100, this.check);
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      getSurvey(this.id).then((res) => {
        this.formList = JSON.parse(res.text);
        this.logicList = JSON.parse(res.logic);
        this.title = res.title;
      });
    }
  },

  methods: {
    check(e) {
      for (let j = 0; j < this.logicList.length; j++) {
        const l = this.logicList[j];
        let t = 0;
        for (let i = 0; i < l.list.length; i++) {
          const a = l.list[i];
          let target =
            this.formList[this.formList.map((item) => item.id).indexOf(a.id)];
          if (a.type == 0) {
            if (target.answer == a.answer) t++;
          } else {
            if (target.answer != a.answer) t++;
          }
        }
        let index = this.formList
          .map((item) => item.id)
          .indexOf(parseInt(l.id));
        if (l.type == 0) {
          t >= l.list.length
            ? this.formList[index].show == true
              ? null
              : this.$set(this.formList[index], "show", true)
            : this.formList[index].show == false
            ? null
            : this.$set(this.formList[index], "show", false);
        } else {
          t > 0
            ? this.formList[index].show == true
              ? null
              : this.$set(this.formList[index], "show", true)
            : this.formList[index].show == false
            ? null
            : this.$set(this.formList[index], "show", false);
        }
      }
    },
    submit() {
      let a = 0;
      this.formList.map((i) => {
        i.type == 9 &&
        i.answer.indexOf("http://") == -1 &&
        i.answer.indexOf("https://") == -1
          ? (a += 1)
          : null;
      });
      this.$refs.form.validate((res) => {
        if (res) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          if (a == 0) {
            submitSurvey(this.id, {
              text: JSON.stringify(this.formList),
            })
              .then((res) => {
                this.$message.success("提交成功");
              })
              .catch((res) => {
                this.$message.error(res.response.data.message);
              })
              .finally((res) => {
                loading.close();
              });
            return;
          }

          try {
            for (let i = 0; i < this.formList.length; i++) {
              if (this.formList[i].type == 9) {
                let spark = new SparkMD5.ArrayBuffer();
                let fileReader = new FileReader();
                let file = Base64toFile(this.formList[i].answer);
                fileReader.readAsArrayBuffer(file.slice(0, file.size));
                fileReader.onload = (e) => {
                  spark.append(e.target.result);
                  let md5 = spark.end();
                  let form = new FormData();
                  form.set("file", file);
                  form.set("md5", md5);
                  uploadImage(form).then((e) => {
                    a = a - 1;
                    this.formList[i].answer = e.file;
                    if (a == 0) {
                      submitSurvey(this.id, {
                        text: JSON.stringify(this.formList),
                      })
                        .then((res) => {
                          this.$message.success("提交成功");
                        })
                        .catch((res) => {
                          this.$message.error(res.response.data.message);
                        })
                        .finally((res) => {
                          loading.close();
                        });
                    }
                  });
                };
              }
            }
          } catch (error) {
            loading.close();
          }
        }
      });
    },
  },
  watch: {
    formList: {
      handler(n, o) {
        this.debounceInit ? this.debounceInit() : null;
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
#view >>> .el-scrollbar__wrap {
  height: 100%;
  overflow-x: hidden;
}
#view >>> .is-horizontal {
  display: none;
}
#view >>> .el-form-item {
  cursor: default;
  border: none;
  padding: 0 13px;
  float: left;
  margin: 10px 0;
  position: relative;
}

#view >>> .el-form-item:hover {
  background: none;
}

#view >>> .el-col > .el-icon-delete {
  color: #f56c6c;
  position: absolute;
  right: 0;
  top: -10px;
  font-size: 22px;
  cursor: pointer;
  display: none;
}
.el-form {
  height: 100%;
}
.phone {
  height: 80vh;
  width: 100vw;
  display: flex;
  justify-content: center;
}
.phone iframe {
  height: 100%;
  width: 25vw;
  background: white;
  border-radius: 10px;
}
</style>
